﻿// -------------------------------------------------------------------------
//    @FileName         :    NFSnsRoleDetailService.cpp
//    @Author           :    gaoyi
//    @Date             :    2025-03-27
//    @Email			:    445267987@qq.com
//    @Module           :    NFSnsRoleDetailService
//
// -------------------------------------------------------------------------

#include "NFSnsRoleDetailService.h"

#include <NFSnsEventDisp.h>
#include <NFSnsRoleDetail.h>
#include <NFSnsServer/NFSnsCommon/NFSnsRoleSimpleService.h>

#define MAX_TICK_ROLE_DETAIL_NUM_PER_Tick 100

NFSnsRoleDetail* NFSnsRoleDetailService::GetRoleDetail(uint64_t ullRoleId)
{
    return NFSnsRoleDetail::GetObjByHashKey(ullRoleId);
}

NFSnsRoleDetail* NFSnsRoleDetailService::AddRoleDetail(uint64_t ullRoleId, const proto_ff::tbSnsRoleDetail* pDbData)
{
    CHECK_NULL_RE_NULL(ullRoleId, pDbData, "pDbData = NULL");
    auto pRoleDetail = GetRoleDetail(ullRoleId);
    if (pRoleDetail)
    {
        return pRoleDetail;
    }

    pRoleDetail = NFSnsRoleDetail::CreateObjByHashKey(ullRoleId);
    CHECK_NULL_RE_NULL(0, pRoleDetail, "CreateObjByHashKey ullRoleId:{}", ullRoleId);

    pRoleDetail->SetRoleId(ullRoleId);
    pRoleDetail->Init();
    pRoleDetail->LoadFromDb(pDbData);

    return pRoleDetail;
}

int NFSnsRoleDetailService::RemoveRoleDetail(uint64_t ullRoleId)
{
    auto pRoleDetail = GetRoleDetail(ullRoleId);
    CHECK_NULL_WF_WARN(0, pRoleDetail, "can't find roleId:{}", ullRoleId);
    return RemoveRoleDetail(pRoleDetail);
}

int NFSnsRoleDetailService::RemoveRoleDetail(NFSnsRoleDetail* pRoleDetail)
{
    CHECK_NULL(0, pRoleDetail);
    pRoleDetail->UnInit();
    NFSnsRoleDetail::DestroyObj(pRoleDetail);
    return 0;
}

int NFSnsRoleDetailService::Tick()
{
    static auto staticlastIter = NFSnsRoleDetail::Begin();
    for (int i = 0; i < MAX_TICK_ROLE_DETAIL_NUM_PER_Tick; i++)
    {
        if (!NFSnsRoleDetail::IsValid(staticlastIter) || staticlastIter == NFSnsRoleDetail::End())
        {
            staticlastIter = NFSnsRoleDetail::Begin();
            if (staticlastIter == NFSnsRoleDetail::End())
            {
                break;
            }
            if (i > NFSnsRoleDetail::GetStaticUsedCount())
            {
                break;
            }
        }

        auto pRoleDetail = &*staticlastIter;
        CHECK_NULL(0, pRoleDetail);
        pRoleDetail->Tick();
        ++staticlastIter;
    }
    return 0;
}

int NFSnsRoleDetailService::LoginRole(NFSnsRoleDetail* pRoleDetail, bool isResume)
{
    CHECK_NULL(0, pRoleDetail);
    pRoleDetail->OnLogin();
    NFSnsEventDisp::OnRoleLogin(pRoleDetail, isResume);
    return 0;
}
